package com.p.lib.common.rx;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.JsonParseException;
import com.p.lib.app.BaseApplication;
import com.p.lib.common.exception.ApiException;
import com.p.lib.common.exception.BaseException;
import com.p.lib.common.exception.ErrorMessageFactory;

import java.net.SocketException;
import java.net.SocketTimeoutException;

import retrofit2.HttpException;

/**
 * Created by Administrator on 2018/5/31 0031.
 */

public class RxErrorHandler {

    private Context mContext;

    public RxErrorHandler(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 装载Error信息
     * @param t
     * @return
     */
    public BaseException handlerError(Throwable t){

        BaseException be = new BaseException();

        if(t instanceof ApiException){
            be.setCode(((ApiException)t).getCode());        //api错误
            be.setMessage(((ApiException)t).getMessage());
        }else if(t instanceof SocketException){
            be.setCode(BaseException.ERROR_SOCKET);         //链接异常
        }else if(t instanceof SocketTimeoutException){
            be.setCode(BaseException.ERROR_SOCKET_TIMEOUT); //链接超时
        }else if(t instanceof JsonParseException){
            be.setCode(BaseException.ERROR_JSONPARSE);      //解析错误
        }else if(t instanceof HttpException){
            be.setCode(((HttpException)t).code());          //http错误
        }else{
            be.setCode(BaseException.ERROR_UNKNOW);         //未知错误.
        }

        if(TextUtils.isEmpty(be.getMessage())){
            be.setMessage(ErrorMessageFactory.create(mContext, be.getCode()));
        }

        return be;
    }

    /**
     * 提示Error信息
     * @param be
     */
    public void showMessage(BaseException be){
//        Toast.makeText(mContext, be.getMessage(), Toast.LENGTH_SHORT).show();
        BaseApplication.toast(be.getMessage());
    }
}
